package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.filter.UserThreadLocal;
import com.drd.dt.modular.dao.UserMapper;
import com.drd.dt.modular.dto.GoodsDetailDTO;
import com.drd.dt.modular.entity.User;
import com.drd.dt.modular.service.TBGoodsService;
import com.drd.dt.properties.DTKPropertyConfig;
import com.drd.dt.properties.HDKPropertyConfig;
import com.drd.dt.properties.HMTKPropertyConfig;
import com.drd.dt.properties.TBLMPropertyConfig;
import com.drd.dt.util.*;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkCouponGetRequest;
import com.taobao.api.request.TbkDgMaterialOptionalRequest;
import com.taobao.api.request.TbkDgOptimusMaterialRequest;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.response.TbkCouponGetResponse;
import com.taobao.api.response.TbkDgMaterialOptionalResponse;
import com.taobao.api.response.TbkDgOptimusMaterialResponse;
import com.taobao.api.response.TbkItemInfoGetResponse;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 淘宝商品模块
 * 2019-10-33 th
 **/
@Transactional
@Service
public class TBGoodsServiceImpl extends ServiceImpl<UserMapper, User> implements TBGoodsService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserMoneyServiceImpl testMoneyService;
    @Autowired
    private HDKPropertyConfig hdkPropertyConfig;
    @Autowired
    private TBLMPropertyConfig tblmPropertyConfig;
    @Autowired
    private HMTKPropertyConfig hmtkPropertyConfig;
    @Autowired
    private FilterGoodsUtil filterGoodsUtil;
    @Autowired
    private DtkServiceImpl dtkService;
    @Autowired
    private DTKPropertyConfig dtkPropertyConfig;
    @Autowired
    private UserMapper userMapper;

    /**
     * 商品详情
     */
    @Override
    public Tip goodsDetail(String itemid, Integer user_id, HttpServletRequest request, String deviceT, String app_version) throws Exception {
        GoodsDetailDTO detailDTO = new GoodsDetailDTO();
        if (!StringUtils.isEmpty(deviceT) && Integer.valueOf(deviceT) == 1) {//ios过审版
            detailDTO = filterGoodsUtil.filterIOSVersion(detailDTO, request, app_version);
        }

        /**************************旧 - 好单裤*****************************************************/
        String dataStr = getGoodsDetail(itemid);
        if (!StringUtils.isEmpty(dataStr)) {
            JSONObject json = JSON.parseObject(dataStr);
            if (json.containsKey("code") && json.getInteger("code") == 1) {
                JSONObject data = json.getJSONObject("data");
                if (null != data) {
                    Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
                    String shoptype = data.containsKey("shoptype") && null != data.getString("shoptype") ? data.getString("shoptype") : ""; //天猫（B） 淘宝店（C）
                    String goodId = data.containsKey("itemid") && null != data.getString("itemid") ? data.getString("itemid") : "";
                    String itemtitle = data.containsKey("itemtitle") && null != data.getString("itemtitle") ? data.getString("itemtitle") : "";
                    String itemprice = data.containsKey("itemprice") && null != data.getString("itemprice") ? data.getString("itemprice") : "";
                    String itemendprice = data.containsKey("itemendprice") && null != data.getString("itemendprice") ? data.getString("itemendprice") : "";
                    String itemsale = data.containsKey("itemsale") && null != data.getString("itemsale") ? data.getString("itemsale") : "";
                    String couponmoney = data.containsKey("couponmoney") && null != data.getString("couponmoney") ? data.getString("couponmoney") : "";
                    String starttime = data.containsKey("couponstarttime") && null != data.getString("couponstarttime") ? data.getString("couponstarttime") : "";
                    String endtime = data.containsKey("couponendtime") && null != data.getString("couponendtime") ? data.getString("couponendtime") : "";
                    String itemdesc = data.containsKey("itemdesc") && null != data.getString("itemdesc") ? data.getString("itemdesc") : "";
                    String itempic = data.containsKey("itempic") && null != data.getString("itempic") ? data.getString("itempic") : "";
                    Date couponstarttimeDate = null;
                    Date couponendtimeDate = null;
                    if (!starttime.equals("")) {
                        couponstarttimeDate = new Date(new Long(starttime) * 1000);
                    }
                    if (!endtime.equals("")) {
                        couponendtimeDate = new Date(new Long(endtime) * 1000);
                    }

                    Double tkrates = data.getDouble("tkrates"); //佣金比例百分比
                    Double aDouble = Double.valueOf(itemendprice);
                    Double commission = aDouble * (tkrates / 100) * reback_money.doubleValue();
                    Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                    Double upcommission = aDouble * (tkrates / 100) * upreback_money.doubleValue();
                    String vipDesc = filterGoodsUtil.vipDesc(upcommission, user_id);
                    detailDTO.setVipDesc(vipDesc);
                    String sellernick = data.getString("sellernick");
                    String userid = data.getString("userid");

                    String couponurl = data.getString("couponurl");
                    if (!StringUtils.isEmpty(couponmoney) && Double.valueOf(couponmoney) > 0) {
                        detailDTO.setIfCoupon(true);
                    }

                    String highCommissionUrl = "";

                    detailDTO.setCouponUrl(couponurl);  // 领卷地址
                    detailDTO.setStoreName(sellernick); //店铺名称
                    detailDTO.setStoreUserId(userid);   //店铺ID
                    detailDTO.setShopType(shoptype);    //店铺类型
                    detailDTO.setGoodsId(goodId);       //商品id
                    detailDTO.setGoodsName(itemtitle);  //商品名称
                    detailDTO.setPrice(itemprice);       //价格
                    detailDTO.setPriceAfterCoupon(itemendprice);  //优惠后价格
                    detailDTO.setSales(itemsale);         //销量
                    detailDTO.setCoupon(couponmoney);     //卷金额
                    detailDTO.setCouponStartTime(couponstarttimeDate != null ? Constant.y_M_d.format(couponstarttimeDate) : null); //圈开始时间
                    detailDTO.setCouponEndTime(couponendtimeDate != null ? Constant.y_M_d.format(couponendtimeDate) : null);   //圈结束时间
                    detailDTO.setCommission(String.format("%.2f", commission));  //佣金
                    detailDTO.setUpcommission(String.format("%.2f", upcommission));  //上一级佣金
                    detailDTO.setGoodsDesc(itemdesc);                           //商品描述
                    detailDTO.setGoodsMainPicture(itempic);                     //主图
                    detailDTO.setType(1);                                       //平台类型
                    detailDTO.setHighCommissionUrl(highCommissionUrl);          //高佣连接

                    String taobao_image = data.containsKey("taobao_image") ? data.getString("taobao_image") : ""; //轮播图
                    List<String> resultList = new ArrayList();
                    if (!StringUtils.isEmpty(taobao_image)) {
                        if (taobao_image.indexOf(",") != -1) {
                            String[] goodsCarouselPictures = taobao_image.split(",");
                            for (String s : goodsCarouselPictures) {
                                resultList.add(s);
                            }
                        } else {
                            resultList.add(taobao_image);
                        }

                    }
                    if (resultList.size() < 1) {
                        resultList.add(itempic);
                    }
                    detailDTO.setGoodsCarouselPictures(resultList);

                    //预览h5
                    detailDTO.setH5Url(tblmPropertyConfig.getIntroduceUrl() + itemid);
                    //相关推荐
                    detailDTO.setRelatedRecommendation(recommendGetStr(new Long(itemid), 10, user_id));
                    //店铺信息
                    Map<String, Object> storeGiveAMark = new HashMap<String, Object>();
                    storeGiveAMark.put("storeName", detailDTO.getStoreName());
                    storeGiveAMark.put("storeUserId", detailDTO.getStoreUserId());
                    storeGiveAMark.put("storeIcon", detailDTO.getStoreIcon());
                    storeGiveAMark.put("storeURL", detailDTO.getStoreURL());
                    detailDTO.setStoreGiveAMark(storeGiveAMark);

                    return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), detailDTO);
                }
            } else {  //好单库没有 订单详情 则去 大淘客查询
                TreeMap<String, String> paraMap = new TreeMap<>();
                paraMap.put("version", dtkPropertyConfig.getVersion());
                paraMap.put("goodsId", itemid);
                paraMap.put("appKey", dtkPropertyConfig.getAppKey());
                paraMap.put("sign", dtkService.getSignStr(paraMap, dtkPropertyConfig.getAppSecret()));
                dataStr = dtkService.sendGet(dtkPropertyConfig.getDateil(), paraMap);
                if (!StringUtils.isEmpty(dataStr)) {
                    json = JSON.parseObject(dataStr);
                    if (null != json && json.containsKey("code") && json.getInteger("code") == 0) {
                        JSONObject data = json.getJSONObject("data");

                        Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
                        String couponurl = data.containsKey("couponurl") ? data.getString("couponurl") : "";
                        String sellernick = data.containsKey("shopName") ? data.getString("shopName") : "";
                        String userid = data.containsKey("sellerId") ? data.getString("sellerId") : "";
                        String goodId = data.containsKey("goodsId") ? data.getString("goodsId") : "";
                        String goodUrl = data.containsKey("itemLink") ? data.getString("itemLink") : "";
                        String itemtitle = data.containsKey("dtitle") ? data.getString("dtitle") : "";
                        String shoptype = "";
                        if (data.containsKey("shopType")) {
                            switch (data.getInteger("shopType")) {
                                case 1:
                                    shoptype = "天猫";
                                    break;
                                case 0:
                                    shoptype = "淘宝";
                                    break;
                            }
                        }
                        Number itemprice = data.containsKey("originalPrice") ? data.getInteger("originalPrice") : 0;
                        Number itemendprice = data.containsKey("actualPrice") ? data.getInteger("actualPrice") : 0;
                        Number itemsale = data.containsKey("monthSales") ? data.getInteger("monthSales") : 0;
                        Number couponmoney = data.containsKey("couponPrice") ? data.getInteger("couponPrice") : 0;
                        String couponstarttimeDate = data.containsKey("couponStartTime") ? data.getString("couponStartTime") : null;
                        String couponendtimeDate = data.containsKey("couponEndTime") ? data.getString("couponEndTime") : null;
                        Boolean ifCoupon = false;
                        if (couponmoney.intValue() > 0.0) {
                            ifCoupon = true;
                        }
                        Double tkrates = data.containsKey("commissionRate") ? data.getDouble("commissionRate") : 0.0; //佣金比例百分比
                        Double commission = itemendprice.doubleValue() * (tkrates / 100) * reback_money.doubleValue();
                        Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                        Double upcommission = itemendprice.doubleValue() * (tkrates / 100) * upreback_money.doubleValue();
                        String vipDesc = filterGoodsUtil.vipDesc(upcommission, user_id);
                        detailDTO.setVipDesc(vipDesc);
                        String itemdesc = data.containsKey("desc") ? data.getString("desc") : null;
                        String itempic = data.containsKey("mainPic") ? data.getString("mainPic") : null;
                        String highCommissionUrl = "";

                        detailDTO.setIfCoupon(ifCoupon);  // 是否有优惠卷
                        detailDTO.setCouponUrl(couponurl);  // 领卷地址
                        detailDTO.setStoreName(sellernick); //店铺名称
                        detailDTO.setStoreUserId(userid);   //店铺ID
                        detailDTO.setShopType(shoptype);    //店铺类型
                        detailDTO.setGoodsId(goodId);       //商品id
                        detailDTO.setGoodsName(itemtitle);  //商品名称
                        detailDTO.setGoodsUrl(goodUrl);  //商品地址
                        detailDTO.setPrice(itemprice.toString());       //价格
                        detailDTO.setPriceAfterCoupon(itemendprice.toString());  //优惠后价格
                        detailDTO.setSales(itemsale.toString());         //销量
                        detailDTO.setCoupon(couponmoney.toString());     //卷金额
                        detailDTO.setCouponStartTime(couponstarttimeDate != null ? couponstarttimeDate : null); //圈开始时间
                        detailDTO.setCouponEndTime(couponendtimeDate != null ? couponendtimeDate : null);   //圈结束时间
                        detailDTO.setCommission(String.format("%.2f", commission));  //佣金
                        detailDTO.setUpcommission(String.format("%.2f", upcommission));  //上一级佣金
                        detailDTO.setGoodsDesc(itemdesc);                           //商品描述
                        detailDTO.setGoodsMainPicture(itempic);                     //主图
                        detailDTO.setType(1);                                       //平台类型
                        detailDTO.setHighCommissionUrl(highCommissionUrl);          //高佣连接

                        String detailPics = data.containsKey("detailPics") ? data.getString("detailPics") : "";
                        List<String> resultList = new ArrayList();
                        if (!StringUtils.isEmpty(detailPics)) {
                            if (detailPics.indexOf(",") != -1) {
                                String[] goodsCarouselPictures = detailPics.split(",");
                                for (String s : goodsCarouselPictures) {
                                    resultList.add(s);
                                }
                            } else {
                                resultList.add(detailPics);
                            }
                        }
                        if (resultList.size() < 1) {
                            resultList.add(itempic);
                        }
                        detailDTO.setGoodsCarouselPictures(resultList);

                        //预览h5
                        detailDTO.setH5Url(tblmPropertyConfig.getIntroduceUrl() + itemid);
                        //相关推荐
                        detailDTO.setRelatedRecommendation(recommendGetStr(new Long(itemid), 10, user_id));
                        //店铺信息
                        Map<String, Object> storeGiveAMark = new HashMap<String, Object>();
                        storeGiveAMark.put("storeName", detailDTO.getStoreName());
                        storeGiveAMark.put("storeUserId", detailDTO.getStoreUserId());
                        storeGiveAMark.put("storeIcon", detailDTO.getStoreIcon());
                        storeGiveAMark.put("storeURL", detailDTO.getStoreURL());
                        detailDTO.setStoreGiveAMark(storeGiveAMark);
                        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), detailDTO);
                    } else {//大淘客没有只能去淘宝开放平台查询  商品信息极度缺失
                        dataStr = infoGetDetail(itemid, request);
                        if (!StringUtils.isEmpty(dataStr)) {
                            JSONObject object = JSONObject.parseObject(dataStr);
                            if (object.containsKey("tbk_item_info_get_response")) {
                                JSONObject tbk_item_info_get_response = object.getJSONObject("tbk_item_info_get_response");
                                if (tbk_item_info_get_response.containsKey("results")) {
                                    JSONObject results = tbk_item_info_get_response.getJSONObject("results");
                                    if (results.containsKey("n_tbk_item") && results.getJSONArray("n_tbk_item").size() > 0) {
                                        JSONObject n_tbk_item = results.getJSONArray("n_tbk_item").getJSONObject(0);

                                        String goodsId = n_tbk_item.containsKey("num_iid") && n_tbk_item.getLong("num_iid") != null ? n_tbk_item.getLong("num_iid") + "" : "";
                                        String goodsName = n_tbk_item.containsKey("title") && n_tbk_item.getString("title") != null ? n_tbk_item.getString("title") : "";
                                        String goodsDesc = "";
                                        String goodsUrl = n_tbk_item.containsKey("item_url") && n_tbk_item.getString("item_url") != null ? n_tbk_item.getString("item_url") : "";

                                        Integer type = 1;//类型（1淘宝 2京东 3拼多多 4唯品会）
                                        String highCommissionUrl = "";//高佣地址
                                        String couponUrl = "";//领券地址
                                        String sales = n_tbk_item.containsKey("volume") && n_tbk_item.getLong("volume") != null ? n_tbk_item.getLong("volume") + "" : "";//销量
                                        String shopType = "淘宝";//店铺类型
                                        String storeName = n_tbk_item.containsKey("nick") && n_tbk_item.getString("nick") != null ? n_tbk_item.getString("nick") : "";//店铺名
                                        String goodsMainPicture = n_tbk_item.containsKey("pict_url") && n_tbk_item.getString("pict_url") != null ? n_tbk_item.getString("pict_url") : "";//主图
                                        List<String> goodsCarouselPictures = new ArrayList<>();//商品轮播图
                                        JSONArray small_images = n_tbk_item.containsKey("containsKey") && n_tbk_item.getJSONArray("containsKey").size() > 0 ? n_tbk_item.getJSONArray("containsKey") : new JSONArray();
                                        for (int i = 0; i < small_images.size(); i++) {
                                            goodsCarouselPictures.add(small_images.getString(i));
                                        }
                                        Boolean ifCoupon = false;//是否有优惠价卷
                                        String price = "0"; //价格
                                        String coupon = "0";//券金额
                                        String couponStartTime = ""; //卷使用开始时间
                                        String couponEndTime = "";//卷使用结束时间
                                        String priceAfterCoupon = "0";//优惠后价格
                                        String commission = "0";//佣金
                                        String upcommission = "0";//上一级佣金
                                        String vipDesc = filterGoodsUtil.vipDesc(Double.parseDouble(upcommission), user_id);//会员升级提示描述

                                        detailDTO.setGoodsId(goodsId);
                                        detailDTO.setGoodsName(goodsName);
                                        detailDTO.setGoodsDesc(goodsDesc);
                                        detailDTO.setGoodsUrl(goodsUrl);
                                        detailDTO.setType(type);
                                        detailDTO.setHighCommissionUrl(highCommissionUrl);
                                        detailDTO.setCouponUrl(couponUrl);
                                        detailDTO.setSales(sales);
                                        detailDTO.setShopType(shopType);
                                        detailDTO.setStoreName(storeName);
                                        detailDTO.setGoodsMainPicture(goodsMainPicture);
                                        detailDTO.setGoodsCarouselPictures(goodsCarouselPictures);
                                        detailDTO.setPrice(price);
                                        detailDTO.setCoupon(coupon);
                                        detailDTO.setCouponStartTime(couponStartTime);
                                        detailDTO.setCouponEndTime(couponEndTime);
                                        detailDTO.setPriceAfterCoupon(priceAfterCoupon);
                                        detailDTO.setCommission(commission);
                                        detailDTO.setUpcommission(upcommission);
                                        detailDTO.setVipDesc(vipDesc);

                                        //预览h5
                                        detailDTO.setH5Url(tblmPropertyConfig.getIntroduceUrl() + itemid);
                                        //相关推荐
                                        detailDTO.setRelatedRecommendation(recommendGetStr(new Long(itemid), 10, user_id));
                                        //店铺信息
                                        Map<String, Object> storeGiveAMark = new HashMap<String, Object>();
                                        storeGiveAMark.put("storeName", detailDTO.getStoreName());
                                        storeGiveAMark.put("storeUserId", detailDTO.getStoreUserId());
                                        storeGiveAMark.put("storeIcon", detailDTO.getStoreIcon());
                                        storeGiveAMark.put("storeURL", detailDTO.getStoreURL());
                                        detailDTO.setStoreGiveAMark(storeGiveAMark);
                                        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), detailDTO);
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }
        return ResultUtil.result(BizExceptionEnum.GOODS_DETAIL_IS_EMPTY.getCode(), BizExceptionEnum.GOODS_DETAIL_IS_EMPTY.getMessage());
    }


    /**
     * 首页推荐商品(淘宝客-推广者-物料精选)
     */
    @Override
    public Tip getRecommendList(Integer page, Integer user_id, String imei, String DeviceT) throws Exception {
        JSONArray result = new JSONArray();
        if (null == page || StringUtils.isEmpty(page)) {
            page = 1;
        }
        String url = tblmPropertyConfig.getUrl();
        String appkey = tblmPropertyConfig.getAppKey();
        String secret = tblmPropertyConfig.getAppSecret();
        String[] adzoneIds = tblmPropertyConfig.getpId().split("_");
        String adzoneId = adzoneIds[adzoneIds.length - 1];
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
        req.setPageNo(Long.valueOf(page));
        req.setAdzoneId(Long.valueOf(adzoneId));
        req.setMaterialId(Long.valueOf(6708));
        if (!TextUtils.isEmpty(imei)) {
            req.setDeviceValue(MD5Utils.MD5Encode(imei, "utf-8"));
            req.setDeviceEncrypt("MD5");
            if (!TextUtils.isEmpty(DeviceT) && DeviceT.equals("0")) {
                req.setDeviceType("IMEI");
            } else {
                req.setDeviceType("IDFA");
            }

        }
        TbkDgOptimusMaterialResponse execute = client.execute(req);
        String resultStr = execute.getBody();
        if (!StringUtils.isEmpty(resultStr)) {
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(resultStr);
            if (jsonObject.containsKey("error_response")) {
                String msg = jsonObject.getJSONObject("error_response").getString("msg");
                return ResultUtil.result(800, msg);
            }
            //平台返佣比例
            Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
            com.alibaba.fastjson.JSONObject result_list = jsonObject.getJSONObject("tbk_dg_optimus_material_response").getJSONObject("result_list");
            com.alibaba.fastjson.JSONArray map_data = result_list.getJSONArray("map_data");
            SimpleDateFormat sdf = Constant.y_M_d;
            map_data.stream().forEach(list -> {
                GoodsDetailDTO detailDTO = new GoodsDetailDTO();
                com.alibaba.fastjson.JSONObject t = JSON.parseObject(JSON.toJSONString(list));
                Double price = t.getDouble("zk_final_price");
                String goodsName = t.getString("title");

                Double coupon_amount = t.getDouble("coupon_amount");  //优惠卷卷额
                Double price_after_coupons = price - coupon_amount;
                Double commission_rate = t.getDouble("commission_rate") / 100;
                Double anti_growth = price_after_coupons * commission_rate * reback_money.doubleValue();
                Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                Double upcommission = price_after_coupons * commission_rate * upreback_money.doubleValue();
                Long coupon_start_time = t.getLong("coupon_start_time"); //优惠卷时间
                Long coupon_end_time = t.getLong("coupon_end_time");
                Long coupon = t.getLong("coupon_amount");
                boolean IfCoupon = false;
                Long date = System.currentTimeMillis();
                if (!StringUtils.isEmpty(coupon_start_time) && !StringUtils.isEmpty(coupon_end_time)) {
                    if (coupon > 0 && (date > coupon_start_time && date < coupon_end_time)) { //判断是否有卷并且 存在有效期
                        IfCoupon = true;
                    }
                    detailDTO.setCouponStartTime(sdf.format(new Date(coupon_start_time)));
                    detailDTO.setCouponEndTime(sdf.format(new Date(coupon_end_time)));
                }
                detailDTO.setIfCoupon(IfCoupon);
                detailDTO.setGoodsName(goodsName);
                detailDTO.setPriceAfterCoupon(String.valueOf(coupon_amount));
                detailDTO.setStoreName(t.getString("nick"));
                detailDTO.setGoodsId(t.getString("item_id"));
                detailDTO.setSales(t.getString("volume"));
                detailDTO.setGoodsMainPicture("http:" + t.getString("pict_url") + "_310x310.jpg");
                detailDTO.setCouponUrl(t.getString("coupon_share_url")); //领券地址
                detailDTO.setType(1);

                detailDTO.setPrice(String.valueOf(price));
                detailDTO.setPriceAfterCoupon(String.format("%.2f", price_after_coupons));
                detailDTO.setCommission(String.format("%.2f", anti_growth));
                detailDTO.setUpcommission(String.format("%.2f", upcommission));
                detailDTO.setCoupon(coupon.toString());

                result.add(detailDTO);
            });
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

    /**
     * 搜索
     */
    @Override
    public Tip goodsSearch(String keyWords, Integer page, String sort, String ifcoupon, Integer user_id, String goods_id) throws Exception {
        TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
        //关键字匹配
        keyWords = StringUtil.getKeyword(keyWords);
        if (!StringUtils.isEmpty(goods_id)) {//智能搜索
            JSONArray result = AISearch(goods_id, user_id);
            if (result.size() > 0) {
                return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
            }
        }
        JSONArray result = new JSONArray();
        req.setPageSize(20L);
        req.setPageNo(Long.valueOf(page));
        // 0是综合 1是最新 2是销量从高到低 4.到手价价格(低到高)，5.到手价价格（高到低）
        if (StringUtils.isEmpty(sort)) {
            sort = "0";
        }
        switch (sort) {
            case "0": {
                sort = "tk_total_sales_des";
            }
            break;
            case "1": {
                sort = "tk_total_sales_asc";
            }
            break;
            case "2": {
                sort = "total_sales_des";
            }
            break;
            case "4": {
                sort = "price_asc";
            }
            break;
            case "5": {
                sort = "price_des";
            }
            break;
        }
        req.setHasCoupon(false); //是否有券
        if (!StringUtils.isEmpty(ifcoupon) && ifcoupon.equals("1")) {
            req.setHasCoupon(true);
        }
        req.setSort(sort);
        req.setQ(keyWords);
        String[] adzoneIds = tblmPropertyConfig.getpId().split("_");
        req.setAdzoneId(Long.valueOf(adzoneIds[adzoneIds.length - 1]));

        boolean flag = false;//标识是否再次请求数据
        Integer number = 0;
        Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
        do {
            String dataStr = getTbOptionalList(req);
            if (!StringUtils.isEmpty(dataStr)) {
                JSONObject dataJSON = JSON.parseObject(dataStr);
                //结果返回错误时
                if (dataJSON.containsKey("error_response") && dataJSON.getJSONObject("error_response").containsKey("sub_code")) {
                    Integer sub_code = dataJSON.getJSONObject("error_response").getInteger("sub_code");
                    if (sub_code == 50001 && number < 4) {//表示搜索无结果并且搜索次数小于四次
                        number++;
                        flag = true;
                    } else {
                        flag = false;
                    }
                }
                if (dataJSON.containsKey("tbk_dg_material_optional_response") && dataJSON.getJSONObject("tbk_dg_material_optional_response").containsKey("result_list")) {
                    flag = false;
                    JSONObject tbk_dg_material_optional_response = dataJSON.getJSONObject("tbk_dg_material_optional_response");
                    JSONObject result_list = tbk_dg_material_optional_response.getJSONObject("result_list");
                    if (null != result_list) {
                        JSONArray map_data = result_list.getJSONArray("map_data");
                        if (null != map_data && map_data.size() > 0) {
                            map_data.stream().forEach(t -> {
                                JSONObject data = (JSONObject) t;
                                String pic_url = data.getString("pict_url");
                                String coupon = data.getString("coupon_amount");
                                String zk_final_price = data.getString("zk_final_price");
                                Double coupon_amount = 0.0;

                                GoodsDetailDTO detailDTO = new GoodsDetailDTO();
                                detailDTO.setIfCoupon(data.getBoolean("has_coupon"));
                                detailDTO.setType(1);//淘宝
                                detailDTO.setGoodsId(data.getString("item_id"));
                                String goodsName = data.getString("title");

                                detailDTO.setGoodsName(goodsName);
                                detailDTO.setGoodsUrl(data.getString("item_url"));
                                detailDTO.setGoodsMainPicture(pic_url + "_310x310.jpg");
                                detailDTO.setSales(data.getString("volume"));
                                detailDTO.setStoreName(data.getString("shop_title"));//店铺名
                                if (data.containsKey("coupon_amount")) {
                                    detailDTO.setCoupon(coupon);
                                    coupon_amount = Double.valueOf(coupon);
                                } else {
                                    detailDTO.setCoupon("0");
                                }
                                if (data.containsKey("zk_final_price")) {
                                    Double final_price = Double.valueOf(zk_final_price);
                                    detailDTO.setPrice(zk_final_price);
                                    detailDTO.setPriceAfterCoupon(String.format("%.2f", final_price - coupon_amount));
                                }
                                double final_price = data.getDouble("zk_final_price") - coupon_amount;
                                double tkrates = Double.valueOf(data.getString("commission_rate"));//佣金比例 百分比

                                double anti_growth = final_price * (tkrates / 10000) * reback_money;
                                double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                                double upcommission = final_price * (tkrates / 10000) * upreback_money;
                                detailDTO.setCommission(String.format("%.2f", anti_growth));
                                detailDTO.setUpcommission(String.format("%.2f", upcommission));
                                detailDTO.setCouponStartTime(data.getString("coupon_start_time"));
                                detailDTO.setCouponEndTime(data.getString("coupon_end_time"));
                                detailDTO.setGoodsDesc(data.getString("item_description"));
                                detailDTO.setType(1);

                                result.add(detailDTO);
                            });
                        }
                    }
                }
            } else {
                throw new BussinessException(BizExceptionEnum.GOODS_LIST_IS_EMPTY);
            }
        } while (flag);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

    /**
     * 好单库搜索（版本替换时使用）
     */
    public Tip goodsSearchByHDK(String keyWords, Integer page, String sort, String ifcoupon, Integer user_id, String goods_id) throws Exception {
        //关键字匹配
        keyWords = StringUtil.getKeyword(keyWords);
        if (!StringUtils.isEmpty(goods_id)) {//智能搜索
            JSONArray result = AISearch(goods_id, user_id);
            if (result.size() > 0) {
                return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
            }
        }
        JSONArray result = new JSONArray();
        // (淘宝联盟)0是综合 1是最新 2是销量从高到低 4.到手价价格(低到高)，5.到手价价格（高到低）
        // (好单库)0.综合(最新) 1.券后价(低到高)，2.券后价（高到低） 4.月销量（高到低）
        if (StringUtils.isEmpty(sort)) {
            sort = "0";
        }
        switch (sort) {//从淘宝联盟排序切换到好单库排序，从好单库拿取商品
            case "2": {
                sort = "4";
            }
            break;
            case "4": {
                sort = "1";
            }
            break;
            case "5": {
                sort = "2";
            }
            break;
        }

        Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);

        String apikey = hdkPropertyConfig.getApiKey();
        String hdk_url = hdkPropertyConfig.getItemlistUrl() + "apikey/" + apikey + "/nav/3/cid/0/back/20/min_id/" + page + "/sort/" + sort;
        String dataStr = HttpConnectionPoolUtil.get(hdk_url);
        if (!StringUtils.isEmpty(dataStr)) {
            JSONObject dataJSON = JSON.parseObject(dataStr);
            if (dataJSON.containsKey("data")) {
                JSONArray map_data = dataJSON.getJSONArray("data");
                if (null != map_data && map_data.size() > 0) {
                    SimpleDateFormat y_m_d = Constant.y_M_d;
                    map_data.stream().forEach(t -> {
                        JSONObject data = (JSONObject) t;
                        String pic_url = data.getString("itempic");
                        String coupon = data.getString("couponmoney");
                        String zk_final_price = data.getString("itemprice");

                        GoodsDetailDTO detailDTO = new GoodsDetailDTO();
                        detailDTO.setIfCoupon(data.getBoolean("has_coupon"));
                        detailDTO.setGoodsId(data.getString("itemid"));
                        String goodsName = data.getString("itemtitle");

                        detailDTO.setGoodsName(goodsName);
                        detailDTO.setGoodsUrl(data.getString("item_url"));
                        detailDTO.setGoodsMainPicture(pic_url + "_310x310.jpg");
                        detailDTO.setSales(data.getString("itemsale"));
                        detailDTO.setStoreName(data.getString("shopname"));//店铺名
                        detailDTO.setGoodsDesc(data.getString("itemdesc"));
                        Double coupon_amount = 0.0;
                        if (data.containsKey("couponmoney")) {
                            detailDTO.setCoupon(coupon);
                            coupon_amount = Double.valueOf(coupon);
                            if (coupon_amount > 0) {
                                detailDTO.setIfCoupon(true);
                            }
                        } else {
                            detailDTO.setCoupon("0");
                        }
                        if (data.containsKey("itemprice")) {
                            Double final_price = Double.valueOf(zk_final_price);
                            detailDTO.setPrice(zk_final_price);
                            detailDTO.setPriceAfterCoupon(String.format("%.2f", final_price - coupon_amount));
                        }
                        double final_price = data.getDouble("itemprice") - coupon_amount;
                        double tkrates = Double.valueOf(data.getString("tkrates"));//佣金比例 百分比

                        double anti_growth = final_price * (tkrates / 100) * reback_money;
                        double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                        double upcommission = final_price * (tkrates / 100) * upreback_money;
                        detailDTO.setCommission(String.format("%.2f", anti_growth));
                        detailDTO.setUpcommission(String.format("%.2f", upcommission));
                        detailDTO.setCouponStartTime(y_m_d.format(new Date(data.getLong("couponstarttime"))));
                        detailDTO.setCouponEndTime(y_m_d.format(new Date(data.getLong("couponendtime"))));
                        detailDTO.setType(1);

                        result.add(detailDTO);
                    });
                }
            }
        } else {
            throw new BussinessException(BizExceptionEnum.GOODS_LIST_IS_EMPTY);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

    /**
     * 商品转高拥
     */
    @Override
    public Tip goodsInfo(String goodsId, String userId, String relationId, Boolean ifCoupon, String buytype, String app_version, String deviceT) throws Exception {
        if (StringUtils.isEmpty(ifCoupon)) {
            ifCoupon = false;
        }
        String relation_id = "";
        String special_id = "";
        User user = UserThreadLocal.get();
        if (null != user) {
            relation_id = user.getTaobao_relation_id();
            special_id = user.getTaobao_special_id();
            if ((buytype.equals("0") && StringUtils.isEmpty(special_id)) || (buytype.equals("1") && StringUtils.isEmpty(relation_id))) {//自购并且会员ID为空，则多等待2秒，再去查
                try {
                    Thread.sleep(2000);
                    User usernow = userMapper.selectById(Integer.valueOf(user.getId()));
                    if (usernow != null) {
                        relation_id = usernow.getTaobao_relation_id();
                        special_id = usernow.getTaobao_special_id();
                    }
                } catch (Exception e) {
                }
            }
        }
        //黑马淘客 高佣转链API
        String mypid = tblmPropertyConfig.getpId();

        if (!StringUtils.isEmpty(buytype)) {//0自购 1来自分享
            if (buytype.equals("1") && !StringUtils.isEmpty(relation_id)) {//分享
                mypid = tblmPropertyConfig.getChanaelId();
            } else if (buytype.equals("0") && !StringUtils.isEmpty(special_id)) { //自购
                mypid = tblmPropertyConfig.getChanaelId();
            }
        }
        String data = this.getHDKGYZL(mypid, goodsId, relation_id, buytype);//好单库高佣
        JSONObject gyJSON = null;
        if (!StringUtils.isEmpty(data)) {
            JSONObject json = JSON.parseObject(data);
            String msg = json.getString("msg");
            if (msg.equals("SUCCESS")) {
                gyJSON = json.getJSONObject("data");
            } else {
                data = getHMTKGYZL(mypid, goodsId, relation_id, buytype);//黑马淘客高佣
                gyJSON = JSON.parseObject(data);
            }
        }
        Map<String, Object> result = new HashMap<>();
        if (null != gyJSON) {
            String url = "";
            if (ifCoupon.equals(false) && gyJSON.containsKey("item_url")) {
                url = gyJSON.getString("item_url");
            } else if (ifCoupon.equals(true) && gyJSON.containsKey("coupon_click_url")) {
                url = gyJSON.getString("coupon_click_url");
            }
            if (StringUtils.isEmpty(url)) {// 商品下架
                return ResultUtil.result(BizExceptionEnum.GOODS_INFO_IS_NULL.getCode(), BizExceptionEnum.GOODS_INFO_IS_NULL.getMessage());
            }
            result.put("url", url);
            result.put("relation_id", relation_id);
            result.put("special_id", special_id);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

    /**
     * 智能解析
     *
     * @param content
     * @return
     * @throws Exception
     */
    @Override
    public Tip analysisContent(String content) throws Exception {
        if (!StringUtils.isEmpty(content)) {
            logger.info("【开始智能解析接口...】");
            // 1 字符串 解析
            String kl = "";
            String itemName = "";
            String itemId = "";
            kl = matchKouling(content);
            //匹配淘口令
            /*String regex = "￥|$|₤|£|₰|₣|₠|ƒ|₭|€|₳|¢|¤|฿|₵|₡|₫|₲|₥|₦|₱|〒|₮|₩|₴|₪|៛|₢|ℳ|₯|₧";
            Pattern patternKL = Pattern.compile("(?<=" + regex + ").*?(?=" + regex + ")");
            Matcher matcherKL = patternKL.matcher(content);
            if (matcherKL.find()) {
                kl += matcherKL.group();
            }*/
            // 1.1  口令
            if (!kl.equals("")) {
                //1.1.1 解析口令
                String apiKey = tblmPropertyConfig.getKlApikey();
                String url = "https://api.taokouling.com/tkl/tkljm?apikey=" + apiKey + "&tkl=￥" + kl + "￥";
                String getData = HttpConnectionPoolUtil.get(url);
                JSONObject jsonObject = JSON.parseObject(getData);
                if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 1 && jsonObject.containsKey("content") && jsonObject.containsKey("url")) {
                    String urlStr = jsonObject.getString("url");
                    String id = "";
                    Pattern pattern2 = Pattern.compile("(?<=taobao.com/).*?(?=.htm)");
                    Matcher matcher2 = pattern2.matcher(urlStr);
                    while (matcher2.find()) {
                        id += matcher2.group();
                    }
                    Pattern patternNum = Pattern.compile("\\d*");
                    Matcher matcherNum = patternNum.matcher(id);
                    while (matcherNum.find()) {
                        itemId += matcherNum.group();
                    }
                    itemName = jsonObject.getString("content");
                }
                //高佣转链
                if (!StringUtils.isEmpty(itemId)) {
                    Tip tip = goodsInfo(itemId, null, "", true, "1", "1.1.1", "0");
                    if (null != tip && tip.getCode() != 200) {
                        itemId = "";
                    }
                }
                // 1.2  标题
            } else if (itemName.equals("") && content.contains("http") == false && content.contains("https") == false) { //http过滤
                //纯数字 过滤
                Pattern patternNum = Pattern.compile("^-?[1-9]\\d*$");
                Matcher matcherNum = patternNum.matcher(content);
                //邮箱过滤
                Pattern patternNum2 = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
                Matcher matcherNum2 = patternNum2.matcher(content);

                if (matcherNum.find() == true || matcherNum2.find() == true) {
                    return ResultUtil.result(BizExceptionEnum.GOODS_CONTENT_IS_NO.getCode(), BizExceptionEnum.GOODS_CONTENT_IS_NO.getMessage(), content);
                } else {
                    itemName = content;
                }
                // 1.3  商品链接
            } else if (content.startsWith("http") && content.contains("id=") && content.contains("?")) {
                String[] split = content.split("\\?");
                if (split.length > 1) {
                    String str = split[1];
                    if (str.contains("&")) {
                        String[] strArr = str.split("&");
                        for (int i = 0; i < strArr.length; i++) {
                            String[] data = strArr[i].split("=");
                            if (data[0].equals("id")) {
                                itemId = data[1];
                            }
                        }
                    } else {
                        String[] data = str.split("=");
                        if (data[0].equals("id")) {
                            itemId = data[1];
                        }
                    }
                }
                itemName = getGoodsName(itemId);//通过id获取商品信息
                // 1.4  其他(复制的错误内容)
            } else {
                logger.info("【" + BizExceptionEnum.GOODS_CONTENT_IS_NO.getMessage() + "】");
                return ResultUtil.result(BizExceptionEnum.GOODS_CONTENT_IS_NO.getCode(), BizExceptionEnum.GOODS_CONTENT_IS_NO.getMessage(), content);
            }


            JSONObject result = new JSONObject();
            result.put("itemName", itemName);//商品标题
            result.put("itemId", itemId); //商品id
            return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
        } else {
            logger.info("【" + BizExceptionEnum.PARAM_EMPTY.getMessage() + "】");
            return ResultUtil.result(BizExceptionEnum.PARAM_EMPTY.getCode(), BizExceptionEnum.PARAM_EMPTY.getMessage());
        }
    }

    private String matchKouling(String content) {
        String pattern = "([\\p{Sc}])\\w{8,12}([\\p{Sc}])";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(content);
        if (m.find()) {
            return m.group();
        }
        return "";
    }

    @Override
    public Tip recommendGet(Long num_iid, Integer user_id) throws Exception {
        List<GoodsDetailDTO> detailDTOList = recommendGetStr(num_iid, 40, user_id);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), detailDTOList);
    }

    @Override
    public Tip sparePostage(int sort, int cid, int page, Integer user_id) throws Exception {
        List<GoodsDetailDTO> goodsDetailDTOList = new ArrayList<GoodsDetailDTO>();
        String apikey = hdkPropertyConfig.getApiKey();
        String hdk_url = hdkPropertyConfig.getColumnUrl() + "apikey/" +
                apikey + "/sort/" + sort + "/cid/" + cid + "/back/20/min_id/" + page + "/type/2";
        String dataStr = HttpConnectionPoolUtil.get(hdk_url);
        if (null != dataStr && !dataStr.equals("")) {
            JSONObject jsonObject = JSONObject.parseObject(dataStr);
            if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 1 && jsonObject.containsKey("data")) {
                JSONArray data = jsonObject.getJSONArray("data");
                Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
                for (int i = 0; i < data.size(); i++) {
                    JSONObject ob = data.getJSONObject(i);

                    GoodsDetailDTO goodsDetailDTO = new GoodsDetailDTO();
                    String goodsId = ob.containsKey("itemid") ? ob.getString("itemid") : "";
                    String goodsName = ob.containsKey("itemtitle") ? ob.getString("itemtitle") : "";
                    String goodsDesc = ob.containsKey("itemdesc") ? ob.getString("itemdesc") : "";
                    String goodsUrl = "";
                    Double coupon = ob.containsKey("couponmoney") ? ob.getDouble("couponmoney") : 0;//券金额
                    Boolean ifCoupon = false;//是否有优惠价卷
                    if (coupon > 0) {
                        ifCoupon = true;
                    }
                    String shopType = "";//店铺类型
                    if (ob.containsKey("shoptype") && ob.getString("shoptype").length() > 0) {
                        switch (ob.getString("shoptype")) {
                            case "B":
                                shopType = "天猫";
                                break;
                            case "C":
                                shopType = "淘宝店";
                                break;
                        }
                    }
                    Integer type = 1;//类型（1淘宝 2京东 3拼多多 4唯品会）
                    String highCommissionUrl = "";//高佣地址
                    String couponUrl = ob.containsKey("couponurl") ? ob.getString("couponurl") : "";//领券地址
                    String couponStartTime = ob.containsKey("couponstarttime") ? ob.getInteger("couponstarttime") + "" : ""; //卷使用开始时间
                    String couponEndTime = ob.containsKey("couponendtime") ? ob.getInteger("couponendtime") + "" : "";//卷使用结束时间
                    Date couponstarttimeDate = null;
                    Date couponendtimeDate = null;
                    if (!couponStartTime.equals("")) {
                        couponstarttimeDate = new Date(new Long(couponStartTime) * 1000);
                    }
                    if (!couponEndTime.equals("")) {
                        couponendtimeDate = new Date(new Long(couponEndTime) * 1000);
                    }

                    String sales = ob.containsKey("itemsale") ? ob.getInteger("itemsale") + "" : "";//销量
                    Double price = ob.containsKey("itemprice") ? ob.getDouble("itemprice") : 0; //价格
                    Double priceAfterCoupon = ob.containsKey("itemendprice") ? ob.getDouble("itemendprice") : 0;//优惠后价格

                    Double tkrates = ob.containsKey("tkrates") ? ob.getDouble("tkrates") : 0;  //佣金比例
                    Double commission = priceAfterCoupon * tkrates / 100 * reback_money.doubleValue();//佣金
                    Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                    Double upcommission = priceAfterCoupon * tkrates / 100 * upreback_money.doubleValue();
                    String storeName = ob.containsKey("shopname") ? ob.getString("shopname") : "";//店铺名
                    String storeUserId = ob.containsKey("userid") ? ob.getString("userid") + "" : "";//店铺ID
                    String goodsMainPicture = ob.containsKey("itempic") ? ob.getString("itempic") : "";//主图
                    goodsMainPicture += "_310x310.jpg";

                    goodsDetailDTO.setGoodsId(goodsId);
                    goodsDetailDTO.setGoodsUrl(goodsUrl);
                    goodsDetailDTO.setGoodsDesc(goodsDesc);
                    goodsDetailDTO.setGoodsName(goodsName);
                    goodsDetailDTO.setIfCoupon(ifCoupon);
                    goodsDetailDTO.setShopType(shopType);
                    goodsDetailDTO.setType(type);
                    goodsDetailDTO.setCouponUrl(couponUrl);
                    goodsDetailDTO.setCouponStartTime(couponstarttimeDate != null ? Constant.y_M_d_H_m_s.format(couponstarttimeDate) : null);
                    goodsDetailDTO.setCouponEndTime(couponendtimeDate != null ? Constant.y_M_d_H_m_s.format(couponendtimeDate) : null);
                    goodsDetailDTO.setSales(sales);
                    goodsDetailDTO.setPrice(String.format("%.2f", price));
                    goodsDetailDTO.setPriceAfterCoupon(String.format("%.2f", priceAfterCoupon));
                    goodsDetailDTO.setCoupon(String.format("%.2f", coupon));
                    goodsDetailDTO.setCommission(String.format("%.2f", commission));
                    goodsDetailDTO.setUpcommission(String.format("%.2f", upcommission));
                    goodsDetailDTO.setStoreName(storeName);
                    goodsDetailDTO.setStoreUserId(storeUserId);
                    goodsDetailDTO.setGoodsMainPicture(goodsMainPicture);

                    goodsDetailDTOList.add(goodsDetailDTO);
                }
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), goodsDetailDTOList);

    }


    @Override
    public Tip supersearchList(String keyword, int sort, int is_coupon, int page, Integer user_id) throws Exception {
        List<GoodsDetailDTO> goodsDetailDTOList = new ArrayList<GoodsDetailDTO>();
        String apikey = hdkPropertyConfig.getApiKey();
        String hdk_url = hdkPropertyConfig.getSupersearchUrl() + "apikey/" +
                apikey + "/keyword/" + keyword + "/sort/" + sort + "/is_coupon/" + is_coupon + "/is_tmall/0/back/20/min_id/" + page + "/tb_p/1/0";
        String dataStr = HttpConnectionPoolUtil.get(hdk_url);
        if (null != dataStr && !dataStr.equals("")) {
            JSONObject da = JSONObject.parseObject(dataStr);
            if (da.containsKey("code") && da.getInteger("code") == 1) {
                JSONArray data = da.getJSONArray("data");
                Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
                if (null != data && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject ob = data.getJSONObject(i);

                        GoodsDetailDTO goodsDetailDTO = new GoodsDetailDTO();
                        String goodsId = ob.containsKey("itemid") ? ob.getString("itemid") : "";
                        String goodsName = ob.containsKey("itemtitle") ? ob.getString("itemtitle") : "";
                        String goodsDesc = ob.containsKey("itemdesc") ? ob.getString("itemdesc") : "";
                        String goodsUrl = "";
                        Double coupon = ob.containsKey("couponmoney") ? ob.getDouble("couponmoney") : 0;//券金额
                        Boolean ifCoupon = false;//是否有优惠价卷
                        if (coupon > 0) {
                            ifCoupon = true;
                        }
                        String shopType = "";//店铺类型
                        if (ob.containsKey("shoptype") && ob.getString("shoptype").length() > 0) {
                            switch (ob.getString("shoptype")) {
                                case "B":
                                    shopType = "天猫";
                                    break;
                                case "C":
                                    shopType = "淘宝店";
                                    break;
                            }
                        }
                        Integer type = 1;//类型（1淘宝 2京东 3拼多多 4唯品会）
                        String highCommissionUrl = "";//高佣地址
                        String couponUrl = ob.containsKey("couponurl") ? ob.getString("couponurl") : "";//领券地址
                        String couponStartTime = ob.containsKey("couponstarttime") ? ob.getString("couponstarttime") : ""; //卷使用开始时间
                        String couponEndTime = ob.containsKey("couponendtime") ? ob.getString("couponendtime") : "";//卷使用结束时间
                        Date couponstarttimeDate = null;
                        Date couponendtimeDate = null;
                        if (!couponStartTime.equals("")) {
                            couponstarttimeDate = new Date(new Long(couponStartTime) * 1000);
                        }
                        if (!couponEndTime.equals("")) {
                            couponendtimeDate = new Date(new Long(couponEndTime) * 1000);
                        }

                        String sales = ob.containsKey("itemsale") ? ob.getInteger("itemsale") + "" : "";//销量
                        Double price = ob.containsKey("itemprice") ? ob.getDouble("itemprice") : 0; //价格
                        Double priceAfterCoupon = ob.containsKey("itemendprice") ? ob.getDouble("itemendprice") : 0;//优惠后价格
                        Double tkrates = ob.containsKey("tkrates") ? ob.getDouble("tkrates") : 0;  //佣金比例
                        Double commission = priceAfterCoupon * tkrates / 100 * reback_money.doubleValue();//佣金
                        Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                        Double upcommission = priceAfterCoupon * tkrates / 100 * upreback_money.doubleValue();//佣金
                        String storeName = ob.containsKey("shopname") ? ob.getString("shopname") : "";//店铺名
                        String storeUserId = ob.containsKey("userid") ? ob.getString("userid") + "" : "";//店铺ID
                        String goodsMainPicture = ob.containsKey("itempic") ? ob.getString("itempic") : "";//主图
                        goodsMainPicture += "_310x310.jpg";


                        goodsDetailDTO.setGoodsId(goodsId);
                        goodsDetailDTO.setGoodsUrl(goodsUrl);
                        goodsDetailDTO.setGoodsDesc(goodsDesc);
                        goodsDetailDTO.setGoodsName(goodsName);
                        goodsDetailDTO.setIfCoupon(ifCoupon);
                        goodsDetailDTO.setShopType(shopType);
                        goodsDetailDTO.setType(type);
                        goodsDetailDTO.setCouponUrl(couponUrl);
                        goodsDetailDTO.setCouponStartTime(couponstarttimeDate != null ? Constant.y_M_d_H_m_s.format(couponstarttimeDate) : null);
                        goodsDetailDTO.setCouponEndTime(couponendtimeDate != null ? Constant.y_M_d_H_m_s.format(couponendtimeDate) : null);
                        goodsDetailDTO.setSales(sales);
                        goodsDetailDTO.setPrice(String.format("%.2f", price));
                        goodsDetailDTO.setPriceAfterCoupon(String.format("%.2f", priceAfterCoupon));
                        goodsDetailDTO.setCoupon(String.format("%.2f", coupon));
                        goodsDetailDTO.setCommission(String.format("%.2f", commission));
                        goodsDetailDTO.setUpcommission(String.format("%.2f", upcommission));
                        goodsDetailDTO.setStoreName(storeName);
                        goodsDetailDTO.setStoreUserId(storeUserId);
                        goodsDetailDTO.setGoodsMainPicture(goodsMainPicture);

                        goodsDetailDTOList.add(goodsDetailDTO);
                    }
                }
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), goodsDetailDTOList);
    }

    /**
     * 淘宝详情商品相关推荐
     */
    private List<GoodsDetailDTO> recommendGetStr(Long num_iid, int count, Integer user_id) throws Exception {
        String apikey = hdkPropertyConfig.getApiKey();
        String hdk_url = hdkPropertyConfig.getSimilarUrl() + "apikey/" +
                apikey + "/itemid/" + num_iid;
        String dataStr = HttpConnectionPoolUtil.get(hdk_url);
        List<GoodsDetailDTO> detailDTOList = new ArrayList<>();
        if (null != dataStr && !dataStr.equals("")) {
            JSONObject jsonObject = JSONObject.parseObject(dataStr);
            if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 1) {
                JSONArray data = jsonObject.getJSONArray("data");


                Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
                if (null != data && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject ob = data.getJSONObject(i);
                        GoodsDetailDTO goodsDetailDTO = new GoodsDetailDTO();

                        String goodsId = ob.containsKey("itemid") && null != ob.getString("itemid") ? ob.getString("itemid") : "";
                        String goodsName = ob.containsKey("itemtitle") && null != ob.getString("itemtitle") ? ob.getString("itemtitle") : "";
                        String goodsDesc = ob.containsKey("itemdesc") && null != ob.getString("itemdesc") ? ob.getString("itemdesc") : "";
                        String goodsUrl = "";
                        Boolean ifCoupon = false;//是否有优惠价卷
                        Integer type = 1;//类型（1淘宝 2京东 3拼多多 4唯品会）
                        String couponUrl = ob.containsKey("couponurl") && null != ob.getString("couponurl") ? ob.getString("couponurl") : "";//领券地址
                        String couponStartTime = ob.containsKey("couponstarttime") ? ob.getString("couponstarttime") : ""; //卷使用开始时间
                        String couponEndTime = ob.containsKey("couponendtime") ? ob.getString("couponendtime") : "";//卷使用结束时间
                        Date couponstarttimeDate = null;
                        Date couponendtimeDate = null;
                        if (!couponStartTime.equals("")) {
                            couponstarttimeDate = new Date(new Long(couponStartTime) * 1000);
                        }
                        if (!couponEndTime.equals("")) {
                            couponendtimeDate = new Date(new Long(couponEndTime) * 1000);
                        }

                        String sales = ob.containsKey("itemsale") ? ob.getString("itemsale") : "";//销量
                        Double price = ob.containsKey("itemprice") ? ob.getDouble("itemprice") : 0f; //价格
                        Double priceAfterCoupon = ob.containsKey("itemendprice") ? ob.getDouble("itemendprice") : 0f;//优惠后价格
                        String coupon = ob.containsKey("couponmoney") ? ob.getString("couponmoney") : "";//券金额
                        Double tkrates = ob.containsKey("tkrates") ? ob.getDouble("tkrates") : 0;  //佣金比例
                        Double commission = (price - priceAfterCoupon) * tkrates / 100 * reback_money.doubleValue();//佣金
                        Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                        Double upcommission = (price - priceAfterCoupon) * tkrates / 100 * upreback_money.doubleValue();//佣金
                        String shopType = "";//店铺类型\
                        //店铺类型：
                        //天猫（B）
                        //淘宝店（C）
                        if (ob.containsKey("shoptype") && null != ob.getString("shoptype")) {
                            switch (ob.getString("shoptype")) {
                                case "B":
                                    shopType = "天猫";
                                    break;
                                case "C":
                                    shopType = "淘宝店";
                                    break;
                            }
                        }
                        String storeName = ob.containsKey("sellernick") ? ob.getString("sellernick") : "";//店铺名
                        String storeUserId = ob.containsKey("userid") ? ob.getString("userid") : "";//店铺ID
                        String storeIcon = "";//店铺icon
                        String storeURL = "";//店铺地址
                        String goodsMainPicture = ob.containsKey("itempic") ? ob.getString("itempic") : "";//主图
                        goodsMainPicture += "_310x310.jpg";

                        goodsDetailDTO.setGoodsId(goodsId);
                        goodsDetailDTO.setGoodsUrl(goodsUrl);
                        goodsDetailDTO.setGoodsDesc(goodsDesc);
                        goodsDetailDTO.setGoodsName(goodsName);
                        goodsDetailDTO.setIfCoupon(ifCoupon);
                        goodsDetailDTO.setShopType(shopType);
                        goodsDetailDTO.setType(type);
                        goodsDetailDTO.setCouponUrl(couponUrl);
                        goodsDetailDTO.setCouponStartTime(couponstarttimeDate != null ? Constant.y_M_d_H_m_s.format(couponstarttimeDate) : null);
                        goodsDetailDTO.setCouponEndTime(couponendtimeDate != null ? Constant.y_M_d_H_m_s.format(couponendtimeDate) : null);
                        goodsDetailDTO.setSales(sales);
                        goodsDetailDTO.setPrice(String.format("%.2f", price));
                        goodsDetailDTO.setPriceAfterCoupon(String.format("%.2f", priceAfterCoupon));
                        goodsDetailDTO.setCoupon(String.format("%.2f", Double.parseDouble(coupon)));
                        goodsDetailDTO.setCommission(String.format("%.2f", commission));
                        goodsDetailDTO.setUpcommission(String.format("%.2f", upcommission));
                        goodsDetailDTO.setStoreName(storeName);
                        goodsDetailDTO.setStoreUserId(storeUserId);
                        goodsDetailDTO.setGoodsMainPicture(goodsMainPicture);

                        detailDTOList.add(goodsDetailDTO);
                    }
                }
            }
        }

        return detailDTOList;
    }

    private String getGoodsName(String itemid) throws Exception {
        String itemtitle = "";
        String dataStr = getGoodsDetail(itemid);
        if (!StringUtils.isEmpty(dataStr)) {
            JSONObject json = JSON.parseObject(dataStr);
            if (json.containsKey("code") && json.getInteger("code") == 1) {
                JSONObject data = json.getJSONObject("data");
                if (null != data) {
                    itemtitle = data.getString("itemtitle");
                }
            }
        }
        return itemtitle;
    }

    /***
     * 根据商品ID 查询店家信息
     * */
    private JSONArray AISearch(String keyWords, Integer user_id) throws Exception {
        String dataStr = getCJSS(keyWords, 1, 20, 1, "0", 0, 0, 0);
        JSONArray result = new JSONArray();
        if (!StringUtils.isEmpty(dataStr)) {
            JSONObject dataJSON = JSON.parseObject(dataStr);
            if (dataJSON.containsKey("code") && dataJSON.getInteger("code") == 1) {
                JSONArray datas = dataJSON.getJSONArray("data");
                //两种 API 两种data 结构
                Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
                for (int i = 0; i < datas.size(); i++) {
                    GoodsDetailDTO detailDTO = new GoodsDetailDTO();
                    JSONObject data = datas.getJSONObject(i);
                    detailDTO.setType(1);
                    detailDTO.setGoodsId(data.getString("itemid"));
                    detailDTO.setGoodsName(data.getString("itemtitle"));
                    detailDTO.setCouponUrl(data.getString("couponurl"));
                    detailDTO.setGoodsMainPicture(data.getString("itempic") + "_310x310.jpg");
                    detailDTO.setPrice(data.getString("itemprice"));
                    Double itemendprice = data.getDouble("itemendprice");
                    detailDTO.setPriceAfterCoupon(String.format("%.2f", itemendprice));
                    Double couponmoney = data.getDouble("couponmoney");
                    if (null != couponmoney && couponmoney > 0) {
                        detailDTO.setCoupon(String.format("%.2f", couponmoney));
                        detailDTO.setIfCoupon(true);
                    }
                    detailDTO.setSales(data.getString("itemsale"));
                    detailDTO.setStoreName(data.getString("sellernick"));
                    detailDTO.setShopType(data.getString("shoptype"));
                    detailDTO.setGoodsDesc(data.getString("itemdesc"));

                    Double tkrates = data.getDouble("tkrates");
                    double anti_growth = Double.valueOf(itemendprice) * (tkrates / 100) * reback_money;
                    double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                    double upcommission = itemendprice * (tkrates / 10000) * upreback_money;
                    detailDTO.setCommission(String.format("%.2f", anti_growth));
                    detailDTO.setUpcommission(String.format("%.2f", upcommission));
                    // 卷时间
                    if (data.containsKey("couponstarttime") && !StringUtils.isEmpty(data.getString("couponstarttime"))) {
                        detailDTO.setCouponStartTime(Constant.y_M_d.format(new Date(Long.valueOf(data.getString("couponstarttime")) * 1000)));
                    }
                    if (data.containsKey("couponendtime") && !StringUtils.isEmpty(data.getString("couponendtime"))) {
                        detailDTO.setCouponEndTime(Constant.y_M_d.format(new Date(Long.valueOf(data.getString("couponendtime")) * 1000)));
                    }
                    result.add(detailDTO);
                }
                Collections.shuffle(result);
            }
        }
        return result;
    }

    /**
     * 好单库高佣转链
     */
    public String getHDKGYZL(String pid, String itemid, String relation_id, String buytype) {
        String url = "http://v2.api.haodanku.com/ratesurl";
        StringBuffer param = new StringBuffer();
        param.append("apikey=youfangou").append("&itemid=").append(itemid).append("&pid=")
                .append(pid).append("&tb_name=").append("鼎荣达2721");
        if (!StringUtils.isEmpty(relation_id) && buytype.equals("1")) {//1来自分享
            param.append("&relation_id=").append(relation_id);
        }
        String dataStr = HttpConnectionPoolUtil.postCommandFromNet2(url, param.toString());
        return dataStr;
    }

    /**
     * 黑马淘客高佣转链
     */
    public String getHMTKGYZL(String pid, String num_iid, String relation_id, String buytype) {
        String appkey = hmtkPropertyConfig.getAppKey();
        String appsecret = hmtkPropertyConfig.getAppSecret();
        String sid = hmtkPropertyConfig.getsId();
        String url = hmtkPropertyConfig.getGyzapi();
        if (!StringUtils.isEmpty(relation_id) && buytype.equals("1")) {//1来自分享
            url += "?appkey=" + appkey + "&appsecret=" + appsecret + "&sid=" + sid + "&pid=" + pid + "&num_iid=" + num_iid +
                    "&relation_id=" + relation_id;
        } else {
            url += "?appkey=" + appkey + "&appsecret=" + appsecret + "&sid=" + sid + "&pid=" + pid + "&num_iid=" + num_iid;
        }
        String dataStr = HttpConnectionPoolUtil.get(url);
        return dataStr;
    }

    /**
     * ( 通用物料搜索API（导购） )taobao.tbk.dg.material.optional
     **/
    public String getTbOptionalList(TbkDgMaterialOptionalRequest req) throws Exception {
        String url = tblmPropertyConfig.getUrl();
        String appkey = tblmPropertyConfig.getAppKey();
        String secret = tblmPropertyConfig.getAppSecret();
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        String data = "";
        try {
            TbkDgMaterialOptionalResponse rsp = client.execute(req);
            data = rsp.getBody();
        } catch (Exception e) {
            logger.info("淘宝数据拉取失败");
        }
        return data;
    }

    /**
     * 高佣API详情
     *
     * @param itemid
     * @return
     * @throws Exception
     */
    public Tip hdkHighCommission(String itemid) throws Exception {
        GoodsDetailDTO detailDTO = new GoodsDetailDTO();
        String gyData = getGYAPI(itemid);
        if (null != gyData && !gyData.equals("")) {
            JSONObject jsonObject = JSON.parseObject(gyData);
            if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 1) {
                JSONObject gyJSONObject = jsonObject.getJSONObject("data");
                if (null != gyJSONObject) {
                    String url = "";
                    if (gyJSONObject.containsKey("item_url") && !gyJSONObject.getString("item_url").equals("")) {
                        url = gyJSONObject.getString("item_url");
                    } else {
                        url = gyJSONObject.getString("coupon_click_url");
                    }
                    detailDTO.setHighCommissionUrl(url);
                }
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), detailDTO);
    }

    /**
     * 高佣API
     **/
    public String getGYAPI(String itemid) throws Exception {
        String apikey = hdkPropertyConfig.getApiKey();
        StringBuffer postData = new StringBuffer();
        postData.append("apikey=");
        postData.append(apikey);
        postData.append("&itemid=");
        postData.append(itemid);
        postData.append("&pid=");
        postData.append(tblmPropertyConfig.getpId());
        postData.append("&tb_name=");
        postData.append(tblmPropertyConfig.getName());
        String gyData = HttpConnectionPoolUtil.postGY(hdkPropertyConfig.getRatesUrl(), postData);
        return gyData;
    }

    /**
     * 调取好单库单品详情API
     **/
    public String getGoodsDetail(String itemid) throws Exception {
        String apikey = hdkPropertyConfig.getApiKey();
        String hdk_url = hdkPropertyConfig.getDetailUrl() + "apikey/" +
                apikey + "/itemid/" + itemid;
        String dataStr = HttpConnectionPoolUtil.get(hdk_url);
        return dataStr;
    }

    /**
     * 商品详情（taobao.tbk.item.info.get）
     */
    public String infoGetDetail(String itemid, HttpServletRequest request) throws Exception {
        TaobaoClient client = new DefaultTaobaoClient(tblmPropertyConfig.getUrl(), tblmPropertyConfig.getAppKey(), tblmPropertyConfig.getAppSecret());
        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
        req.setNumIids(itemid);
        req.setPlatform(1L);
        req.setIp(StringUtil.getIpAddr(request));
        TbkItemInfoGetResponse rsp = client.execute(req);
        return rsp.getBody();
    }

    /***
     * taobao.tbk.coupon.get( 淘宝客-公用-阿里妈妈推广券详情查询 )
     * */
    public String couponGet(String itemid) throws Exception {
        TaobaoClient client = new DefaultTaobaoClient(tblmPropertyConfig.getUrl(), tblmPropertyConfig.getAppKey(), tblmPropertyConfig.getAppSecret());
        TbkCouponGetRequest req = new TbkCouponGetRequest();
        req.setItemId(new Long(itemid));
        TbkCouponGetResponse rsp = client.execute(req);
        return rsp.getBody();
    }

    /***
     * 淘宝客商品详情（简版）
     * */
    public String getTbDetail(String num_iids) throws Exception {
        String url = tblmPropertyConfig.getUrl();
        String appkey = tblmPropertyConfig.getAppKey();
        String secret = tblmPropertyConfig.getAppSecret();
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
        req.setNumIids(num_iids);
        TbkItemInfoGetResponse rsp = client.execute(req);
        String data = rsp.getBody();
        return data;
    }

    /**
     * 关键词商品页API
     */
    private String getGJCSPY(String keyword, int minId, int type) throws Exception {
        String apikey = hdkPropertyConfig.getApiKey();
        String hdk_url = hdkPropertyConfig.getKeyworditemsUrl() + "apikey/" +
                apikey + "/keyword/" + URLEncoder.encode(URLEncoder.encode(keyword, "UTF-8"), "UTF-8") + "/back/20/sort/0/min_id/" + minId + "/cid/0/type/" + type;
        String dataStr = HttpConnectionPoolUtil.get(hdk_url);
        return dataStr;
    }

    private String getCJSS(String keyword, int minId, int back, int tpP, String sort, int isTmall, int isCoupon, int limitrate) throws Exception {
        //设置请求默认参数
        String apikey = hdkPropertyConfig.getApiKey();
        String hdk_url = hdkPropertyConfig.getSupersearchUrl() +
                "apikey/" + apikey + "/keyword/" + URLEncoder.encode(URLEncoder.encode(keyword, "UTF-8"), "UTF-8") + "/back/" + back + "/min_id/" + minId +
                "/tb_p/" + tpP + "/sort/" + sort + "/is_tmall/" + isTmall + "/is_coupon/" + isCoupon + "/limitrate/" + limitrate;
        String dataStr = HttpConnectionPoolUtil.get(hdk_url);

        return dataStr;
    }


    /**
     * 高佣精品(淘宝客-推广者-物料精选)
     */
    @Override
    public Tip supersearchLis2(Integer page, Integer user_id, String imei, String DeviceT) throws Exception {
        JSONArray result = new JSONArray();
        if (null == page || StringUtils.isEmpty(page)) {
            page = 1;
        }
        String url = tblmPropertyConfig.getUrl();
        String appkey = tblmPropertyConfig.getAppKey();
        String secret = tblmPropertyConfig.getAppSecret();
        String[] adzoneIds = tblmPropertyConfig.getpId().split("_");
        String adzoneId = adzoneIds[adzoneIds.length - 1];
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        TbkDgOptimusMaterialRequest req = new TbkDgOptimusMaterialRequest();
        req.setPageNo(Long.valueOf(page));
        req.setAdzoneId(Long.valueOf(adzoneId));
        req.setMaterialId(Long.valueOf(13366));//高佣精品
        if (!TextUtils.isEmpty(imei)) {
            req.setDeviceValue(MD5Utils.MD5Encode(imei, "utf-8"));
            req.setDeviceEncrypt("MD5");
            if (!TextUtils.isEmpty(DeviceT) && DeviceT.equals("0")) {
                req.setDeviceType("IMEI");
            } else {
                req.setDeviceType("IDFA");
            }

        }
        TbkDgOptimusMaterialResponse execute = client.execute(req);
        String resultStr = execute.getBody();
        if (!StringUtils.isEmpty(resultStr)) {
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(resultStr);
            if (jsonObject.containsKey("error_response")) {
                String msg = jsonObject.getJSONObject("error_response").getString("msg");
                return ResultUtil.result(800, msg);
            }
            //平台返佣比例
            Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
            com.alibaba.fastjson.JSONObject result_list = jsonObject.getJSONObject("tbk_dg_optimus_material_response").getJSONObject("result_list");
            com.alibaba.fastjson.JSONArray map_data = result_list.getJSONArray("map_data");
            SimpleDateFormat sdf = Constant.y_M_d;
            map_data.stream().forEach(list -> {
                GoodsDetailDTO detailDTO = new GoodsDetailDTO();
                com.alibaba.fastjson.JSONObject t = JSON.parseObject(JSON.toJSONString(list));
                Double price = t.getDouble("zk_final_price");
                String goodsName = t.getString("title");

                Double coupon_amount = t.getDouble("coupon_amount");  //优惠卷卷额
                Double price_after_coupons = price - coupon_amount;
                Double commission_rate = t.getDouble("commission_rate") / 100;
                Double anti_growth = price_after_coupons * commission_rate * reback_money.doubleValue();
                Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                Double upcommission = price_after_coupons * commission_rate * upreback_money.doubleValue();
                Long coupon_start_time = t.getLong("coupon_start_time"); //优惠卷时间
                Long coupon_end_time = t.getLong("coupon_end_time");
                Long coupon = t.getLong("coupon_amount");
                boolean IfCoupon = false;
                Long date = System.currentTimeMillis();
                if (!StringUtils.isEmpty(coupon_start_time) && !StringUtils.isEmpty(coupon_end_time)) {
                    if (coupon > 0 && (date > coupon_start_time && date < coupon_end_time)) { //判断是否有卷并且 存在有效期
                        IfCoupon = true;
                    }
                    detailDTO.setCouponStartTime(sdf.format(new Date(coupon_start_time)));
                    detailDTO.setCouponEndTime(sdf.format(new Date(coupon_end_time)));
                }
                detailDTO.setIfCoupon(IfCoupon);
                detailDTO.setGoodsName(goodsName);
                detailDTO.setPriceAfterCoupon(String.valueOf(coupon_amount));
                detailDTO.setStoreName(t.getString("nick"));
                detailDTO.setGoodsId(t.getString("item_id"));
                detailDTO.setSales(t.getString("volume"));
                detailDTO.setGoodsMainPicture("http:" + t.getString("pict_url") + "_310x310.jpg");
                detailDTO.setCouponUrl(t.getString("coupon_share_url"));
                detailDTO.setType(1);

                detailDTO.setPrice(String.valueOf(price));
                detailDTO.setPriceAfterCoupon(String.format("%.2f", price_after_coupons));
                detailDTO.setCommission(String.format("%.2f", anti_growth));
                detailDTO.setUpcommission(String.format("%.2f", upcommission));
                detailDTO.setCoupon(coupon.toString());

                result.add(detailDTO);
            });
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

}
